<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Http\Controllers\Controller;
use App\Models\AgentUser;
use App\Models\AssetKey;

class AssetKeyController extends Controller
{
    /** 查询权益码列表 */
    public function index()
    {
        $query = AssetKey::query()
            ->whereHas('asset.user', function ($q) {
                /** @var AgentUser $agentUser */
                $agentUser = auth()->user();

                return $q->where('agent_id', $agentUser->agent_id);
            })
            ->with(['asset.user'])
            ->when(request()->keyword, function ($q) {
                $likeVal = '%' . request()->keyword . '%';

                return $q->where('key', 'like', $likeVal)
                    ->orWhere('prev_code', 'like', $likeVal)
                    ->orWhereHas('asset', function ($q2) use ($likeVal) {
                        return $q2->where('token_id', 'like', $likeVal);
                    });
            })
            ->orderByDesc('id');

        return paginate_result($query);
    }
}
